package com.intelligent.controller;

import com.intelligent.dto.RolePageQueryDTO;
import com.intelligent.dto.RolePermissionUpdateDTO;
import com.intelligent.entity.Permission;
import com.intelligent.entity.Role;
import com.intelligent.entity.RolePermission;
import com.intelligent.service.PermissionService;
import com.intelligent.service.RolePermissionService;
import com.intelligent.service.TRoleService;
import com.intelligent.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/")
public class RoleController {
    @Autowired
    TRoleService roleService;
    
    @Autowired
    PermissionService permissionService;
    
    @Autowired
    RolePermissionService rolePermissionService;
    
    /**
     * 获取所有角色列表（不分页）
     */
    @GetMapping("role")
    public Result<List<Role>> list() {
        return Result.success(roleService.list());
    }
    
    /**
     * 获取所有角色（适配前端请求）
     */
    @GetMapping("/role/list")
    public Result<List<Role>> getAllRoles() {
        List<Role> roles = roleService.list();
        return Result.success(roles);
    }
    
    /**
     * 分页查询角色列表
     */
    @PostMapping("/page")
    public Result<Map<String, Object>> page(@RequestBody RolePageQueryDTO query) {
        Map<String, Object> data = roleService.pageRoles(query);
        return Result.success(data);
    }
    
    /**
     * 分页查询角色列表（适配前端请求）
     */
    @PostMapping("/role/page")
    public Result<Map<String, Object>> rolePage(@RequestBody RolePageQueryDTO query) {
        Map<String, Object> data = roleService.pageRoles(query);
        return Result.success(data);
    }
    
    /**
     * 根据ID获取角色详情
     */
    @GetMapping("/detail")
    public Result<Role> detail(@RequestParam("id") Long id) {
        Role role = roleService.getById(id);
        if (role == null) {
            return Result.error("角色不存在");
        }
        return Result.success(role);
    }
    
    /**
     * 根据ID获取角色详情（适配前端请求）
     */
    @GetMapping("/role/detail")
    public Result<Role> roleDetail(@RequestParam("id") Long id) {
        Role role = roleService.getById(id);
        if (role == null) {
            return Result.error("角色不存在");
        }
        return Result.success(role);
    }
    
    /**
     * 新增角色
     */
    @PostMapping("/add")
    public Result<Void> add(@RequestBody Role role) {
        roleService.addRole(role);
        return Result.success("添加成功");
    }

    /**
     * 保存角色（PUT方法 - 通用保存接口）
     */
    @PutMapping("/save")
    public Result<Void> saveByPut(@RequestBody Role role) {
        if (role.getRoleId() != null) {
            roleService.updateRole(role);
            return Result.success("更新成功");
        } else {
            roleService.addRole(role);
            return Result.success("保存成功");
        }
    }
    
    /**
     * 保存角色
     */
    @PostMapping("/role/save")
    public Result<Void> saveRole(@RequestBody Role role) {
        roleService.addRole(role);
        return Result.success("保存成功");
    }

    /**
     * 保存角色（PUT方法）
     */
    @PutMapping("/role/save")
    public Result<Void> saveRoleByPut(@RequestBody Role role) {
        if (role.getRoleId() != null) {
            roleService.updateRole(role);
            return Result.success("更新成功");
        } else {
            roleService.addRole(role);
            return Result.success("保存成功");
        }
    }
    
    /**
     * 更新角色
     */
    @PutMapping("/role")
    public Result<Void> update(@RequestBody Role role) {
        roleService.updateRole(role);
        return Result.success("更新成功");
    }
    
    /**
     * 删除角色
     */
    @DeleteMapping("/delete")
    public Result<Void> delete(@RequestParam("id") Long id) {
        roleService.deleteRole(id);
        return Result.success("删除成功");
    }
    
    /**
     * 新增角色（适配前端请求 - /role路径）
     */
    @PostMapping("/role")
    public Result<Void> addRole(@RequestBody Role role) {
        roleService.addRole(role);
        return Result.success("添加成功");
    }

    /**
     * 根据ID删除角色（适配前端请求）
     */
    @DeleteMapping("/role")
    public Result<Void> deleteRole(@RequestParam("id") Long id) {
        roleService.deleteRole(id);
        return Result.success("删除成功");
    }
    
    /**
     * 获取所有权限列表
     */
    @GetMapping("/permissions")
    public Result<List<Permission>> getAllPermissions() {
        return Result.success(permissionService.list());
    }
    
    /**
     * 获取所有权限列表（适配前端请求）
     */
    @GetMapping("/permission/list")
    public Result<List<Permission>> getAllPermissionsList() {
        List<Permission> permissions = permissionService.list();
        return Result.success(permissions);
    }
    
    /**
     * 获取分组的权限列表
     * 返回格式：[ { groupId: 1, groupName: '商品管理', children: [ { id: 101, name: '新建商品' }, ... ] }, ... ]
     */
    @GetMapping("/permission/groups")
    public Result<List<Map<String, Object>>> listPermissionGroups() {
        // 1. 获取所有权限
        List<Permission> allPermissions = permissionService.list();
        
        // 2. 按parentId分组，找出所有顶级权限（parentId=0）
        Map<Long, List<Permission>> permissionMap = allPermissions.stream()
                .collect(Collectors.groupingBy(Permission::getParentId));
        
        List<Permission> topLevelPermissions = permissionMap.getOrDefault(0L, new ArrayList<>());
        
        // 3. 构建分组结果
        List<Map<String, Object>> result = new ArrayList<>();
        for (Permission parent : topLevelPermissions) {
            Map<String, Object> group = new HashMap<>();
            group.put("groupId", parent.getPermissionId());
            group.put("groupName", parent.getPermissionName());
            
            // 获取该分组下的子权限
            List<Permission> children = permissionMap.getOrDefault(parent.getPermissionId(), new ArrayList<>());
            List<Map<String, Object>> childrenList = new ArrayList<>();
            
            for (Permission child : children) {
                Map<String, Object> childMap = new HashMap<>();
                childMap.put("id", child.getPermissionId());
                childMap.put("name", child.getPermissionName());
                childrenList.add(childMap);
            }
            
            group.put("children", childrenList);
            result.add(group);
        }
        
        return Result.success(result);
    }
    
    /**
     * 根据ID获取权限详情
     */
    @GetMapping("/permission/{id}")
    public Result<Permission> getPermissionById(@PathVariable("id") Long id) {
        Permission permission = permissionService.getById(id);
        if (permission == null) {
            return Result.error("权限不存在");
        }
        return Result.success(permission);
    }
    
    /**
     * 获取扁平化的权限列表
     */
    @GetMapping("/permission/flat")
    public Result<List<Permission>> getPermissionFlat() {
        List<Permission> permissions = permissionService.list();
        return Result.success(permissions);
    }
    
    /**
     * 获取角色的权限ID列表
     */
    @GetMapping("/permissions/{roleId}")
    public Result<List<Long>> getRolePermissions(@PathVariable("roleId") Long roleId) {
        // 查询角色的权限关联记录
        List<RolePermission> rolePermissions = rolePermissionService.lambdaQuery()
                .eq(RolePermission::getRoleId, roleId)
                .list();
        
        // 提取权限ID列表
        List<Long> permissionIds = rolePermissions.stream()
                .map(RolePermission::getPermissionId)
                .collect(Collectors.toList());
        
        return Result.success(permissionIds);
    }
    
    /**
     * 获取角色的权限ID列表（适配前端请求 - GET方法）
     */
    @GetMapping("/role/permissions/get")
    public Result<List<Long>> getRolePermissionsByParam(@RequestParam("roleId") Long roleId) {
        // 查询角色的权限关联记录
        List<RolePermission> rolePermissions = rolePermissionService.lambdaQuery()
                .eq(RolePermission::getRoleId, roleId)
                .list();
        
        // 提取权限ID列表
        List<Long> permissionIds = rolePermissions.stream()
                .map(RolePermission::getPermissionId)
                .collect(Collectors.toList());
        
        return Result.success(permissionIds);
    }
    

    
    /**
     * 获取角色的权限ID列表（适配前端请求 - POST方法）
     */
    @PostMapping("/role/permissions/query")
    public Result<List<Long>> getRolePermissionsByPost(@RequestBody Map<String, Object> requestMap) {
        Long roleId = Long.valueOf(requestMap.get("roleId").toString());
        
        // 查询角色的权限关联记录
        List<RolePermission> rolePermissions = rolePermissionService.lambdaQuery()
                .eq(RolePermission::getRoleId, roleId)
                .list();
        
        // 提取权限ID列表
        List<Long> permissionIds = rolePermissions.stream()
                .map(RolePermission::getPermissionId)
                .collect(Collectors.toList());
        
        return Result.success(permissionIds);
    }
    
    /**
     * 更新角色权限
     */
    @PostMapping("/permissions/{roleId}")
    public Result<Void> updateRolePermissions(
            @PathVariable("roleId") Long roleId,
            @RequestBody List<Long> permissionIds) {
        return updateRolePermissionsLogic(roleId, permissionIds);
    }

    /**
     * 更新角色权限（PUT方法）
     */
    @PutMapping("/permissions/{roleId}")
    public Result<Void> updateRolePermissionsByPut(
            @PathVariable("roleId") Long roleId,
            @RequestBody List<Long> permissionIds) {
        return updateRolePermissionsLogic(roleId, permissionIds);
    }

    /**
     * 角色权限更新的通用逻辑
     */
    private Result<Void> updateRolePermissionsLogic(Long roleId, List<Long> permissionIds) {
        
        // 1. 删除该角色的所有现有权限关联
        rolePermissionService.lambdaUpdate()
                .eq(RolePermission::getRoleId, roleId)
                .remove();
        
        // 2. 添加新的权限关联
        if (permissionIds != null && !permissionIds.isEmpty()) {
            List<RolePermission> rolePermissions = new ArrayList<>();
            for (Long permissionId : permissionIds) {
                RolePermission rp = new RolePermission();
                rp.setRoleId(roleId);
                rp.setPermissionId(permissionId);
                rolePermissions.add(rp);
            }
            rolePermissionService.saveBatch(rolePermissions);
        }
        
        return Result.success("权限更新成功");
    }
    
    /**
     * 保存角色权限（PUT方法 - 兼容save路径）
     */
    @PutMapping("/role/permissions/batch-save")
    public Result<Void> saveRolePermissionsByPut(@RequestBody Map<String, Object> requestMap) {
        Object roleIdObj = requestMap.get("roleId");
        Object permissionIdsObj = requestMap.get("permissionIds");
        
        if (roleIdObj == null) {
            return Result.error("角色ID不能为空");
        }
        
        Long roleId = Long.valueOf(roleIdObj.toString());
        List<Long> permissionIds = new ArrayList<>();
        
        if (permissionIdsObj instanceof List) {
            List<?> list = (List<?>) permissionIdsObj;
            for (Object item : list) {
                if (item != null) {
                    permissionIds.add(Long.valueOf(item.toString()));
                }
            }
        }
        
        return updateRolePermissionsLogic(roleId, permissionIds);
    }

    /**
     * 更新角色权限（适配前端请求）
     * 支持两种格式：
     * 1. { roleId, permissionIds: [] } - 标准格式
     * 2. { roleId, permissions: [] } - legacy格式
     */
    @PutMapping("/role/permissions/update")
    public Result<Void> updateRolePermissionsByPut(@RequestBody Map<String, Object> requestMap) {
        // 提取roleId
        Long roleId = Long.valueOf(requestMap.get("roleId").toString());
        
        // 提取权限ID列表，支持两种格式
        List<Long> permissionIds = new ArrayList<>();
        if (requestMap.containsKey("permissionIds")) {
            // 标准格式：{ roleId, permissionIds: [] }
            List<?> ids = (List<?>) requestMap.get("permissionIds");
            for (Object id : ids) {
                permissionIds.add(Long.valueOf(id.toString()));
            }
        } else if (requestMap.containsKey("permissions")) {
            // legacy格式：{ roleId, permissions: [] }
            List<?> permissions = (List<?>) requestMap.get("permissions");
            for (Object id : permissions) {
                permissionIds.add(Long.valueOf(id.toString()));
            }
        }
        
        // 1. 删除该角色的所有权限关联
        rolePermissionService.lambdaUpdate()
                .eq(RolePermission::getRoleId, roleId)
                .remove();
        
        // 2. 重新添加权限关联
        if (!permissionIds.isEmpty()) {
            List<RolePermission> rolePermissions = new ArrayList<>();
            for (Long permissionId : permissionIds) {
                RolePermission rp = new RolePermission();
                rp.setRoleId(roleId);
                rp.setPermissionId(permissionId);
                rolePermissions.add(rp);
            }
            rolePermissionService.saveBatch(rolePermissions);
        }
        
        return Result.success("更新成功");
    }
}
